<?php

    class VoteController extends Controller { 
         public $verifyCode;
        

        /**
         * Specifies the access control rules.
         * This method is used by the 'accessControl' filter.
         * @return array access control rules
         */
        public function accessRules() {
            return array(
                array('allow', // allow all users to perform 'index' and 'view' actions
                    'actions' => array('report','index', 'info','captcha','notice','addpull','postComment','getPoll'),
                    'users' => array('*'),
                ),
                array('deny', // deny all users
                    'users' => array('*'),
                ),
            );
        }
 
        public function actions(){
                return array(
                    'captcha'=>array(
                        'class'=>'CaptchaExtendedAction', 
                         'minLength' => 4,
                         'maxLength' => 4, 
                    ),
                );
            }


        /**
        * undocumented function
        *
        * @return void
        * @author 
        **/
        public function actionReport()
        {
            $model=Candidate::model()->findAll(array('order'=>"numbers"));
            foreach ($model as $key => $value) {
                $users[] = $value->numbers.'号<br>'.$value->title;
                $polls[] = intval($value->poll);
            }

            $this->renderPartial('report' , array(
                
                'user' => $users,
                'polls' => $polls,
            ) );
        }


        public function actionNotice() {
            //获取ip
            $this->renderPartial('notice', array(
                'model' => "",
            ));
        }

        public function actionIndex() {
            //获取ip
            $ip = $this->getIP();
            $candidate = new Candidate();
            $dataProvider = $candidate->findAll(array('order' =>'numbers'));
            $this->renderPartial('index', array(
                'dataProvider' => $dataProvider,
            ));
        }

        public function actionInfo($id) {
            $candidate = new Candidate();
            $picture = new Picture(); 
            $info = $candidate->find('id=:id', array(':id' => $id));
            //将用户的点击量+1
            $info->hit = $info->hit + 1;
            $info->save();
            
            $pics = $picture->findAll('cand_id=:id', array(':id' => $id));

             //分页显示留言
             $criteria = new CDbCriteria();    
             $criteria->compare('candidateid',$id);
             $criteria->order = 'createtime desc';        
             $count = Comment::model()->count($criteria);

             $pager = new CPagination($count);    
             $pager->pageSize = 10;             
             $pager->applyLimit($criteria);   
             $comments = Comment::model()->findAll($criteria);   
             //$comments = Comment::model()->findAll('candidateid=' . $id . ' order by id desc'); 
            $this->renderPartial('info', array('info' => $info, 'pics' => $pics, 'pages'=>$pager,'comments' => $comments));
        }

        public function actionAddpull() {  

          //  echo json_encode(array('code'=> -1, 'message'=> "投票已经截止,请勿再投票了！"));
            //exit;

            $reutnmessage = $this->VwCheckReferer();
            if(!empty($reutnmessage) ){
               echo json_encode(array('code'=> -1, 'message'=> $reutnmessage));
               exit; 
            } 

            $captcha = $this->createAction('captcha');
            if(! $captcha->validate($_POST['capthcavalue'], false)){
                echo json_encode(array('code'=> -1 , 'message'=> "验证码错误，请重新投票"));
                exit;
            }

            $captcha->generateVerifyCode();
            
            $id = $_POST['id']; 

            //判断是否有cookies 
           // if(empty($_POST['cookies'])){
           //     echo json_encode(array('code'=> -1, 'message'=> "谢谢参与。"));
           //     exit; 
           //  }  
            //判断传进来的Cookie 是否已经投过
            $cookievalue = $_POST['cookies'];
            $valis = Validation::model()->findAll(' value="' . $cookievalue . '" and to_days(NOW()) = to_days(createtime)'); 
            if(!empty($valis) && count($valis) >= 3) {
                echo json_encode(array('code'=> -1 ,'message'=> "今天已投票次数以上限，谢谢参与", ));
                exit;
            }
             //如果count 不为空 得到id
            if (!count($valis) == 0) {
                //判断被投票人是否投过 投过return 
                foreach ($valis as $v) {
                    $pollList = Poll::model()->find('id=:id', array(':id' => $v['pollid']));
                        if ($pollList->candidateid == $id) {
                            echo json_encode(array('code'=> -2 ,'message'=> "今天已投过该选手，谢谢参与", ));
                            exit;
                        }
                }
            }
            //得到IP是否当天超过3次 超过return 
            $ip = $this->getIP();
            $vali = Validation::model()->findAll(' value="' . $ip . '" and to_days(NOW()) = to_days(createtime)');
            $count = count($vali);
            if (!empty($vali) && $count >= 3) {
                echo json_encode(array('code'=> -1 ,'message'=> "今天已投票次数以上限，谢谢参与", ));
                exit;
            }
            //如果count 不为空 得到id
            if (!$count == 0) {
                //判断被投票人是否投过 投过return 
                foreach ($vali as $v) {
                    $pollList = Poll::model()->find('id=:id', array(':id' => $v['pollid']));
                        if ($pollList->candidateid == $id) {
                            echo json_encode(array('code'=> -2 ,'message'=> "今天已投过该选手，谢谢参与", ));
                            exit;
                        }
                }
            }

            //判断一秒钟只能投一次
            Yii::app()->format->datetimeFormat='Y-m-d H:i:s';
            $newtime=Yii::app()->format->formatDateTime(time()); 
            //查询当前时间是否已经存在数据
            $pollat = Poll::model()->find('candidateid = :candidateid and createtime= :createtime', array(':candidateid'=>$id,':createtime'=>$newtime));
            if(!empty($pollat)){
                echo json_encode(array('code'=> -1 , 'message'=> "同一时间同一选手只能得到一票,请重新投票"));
                exit;
            }
           
            //insert poll table
            $poll = new Poll();
            $poll->candidateid = $id; 
            $poll->createtime = $newtime;
            $poll->save();
            //insert validation ip table
            $validation = new Validation();
            $validation->pollid = $poll->id;
            $validation->type = 'ip';
            $validation->value = $ip; 
            $validation->createtime =$newtime;
            $validation->save();
            //insert validation cookie table
            $validation = new Validation();
            $validation->pollid = $poll->id;
            $validation->type = 'cookie';
            $validation->value = $cookievalue; 
            $validation->createtime = $newtime;
            $validation->save();
            //update candidate table
           
            $cand = Candidate::model()->findByPk($id);
            $cand->poll = count(Poll::model()->findAll('candidateid=:id', array(':id' => $id)));
            $cand->save();
            echo json_encode(array('code'=> 0,'poll'=>$cand->poll ,'message'=> "谢谢参与", ));
        }

        public function actionPostComment() {

            echo json_encode(array('code'=> -1, 'message'=> "投票已经截止,请勿再发布评论了！"));
            exit;

             Yii::app()->format->datetimeFormat='Y-m-d H:i:s';
            $comment = new Comment();
            $comment->username = $_POST['email'];
            $comment->avatar = "images/w/defule.jpg";
            $comment->email = $_POST['email'];
            $comment->content = $_POST['content'];
            $comment->candidateid = $_POST['candidateid'];
            $comment->createtime = Yii::app()->format->formatDateTime(time());
            if($comment->save()){
               echo json_encode(array('code'=> 0, 'message'=> "评论成功!"));
                exit;
            }
            echo json_encode(array('code'=> -1, 'message'=> "评论失败,请重新提交!"));
                exit;
        } 

        /**
         * 得到选手的排名
         *
         * @return void
         * @author 
         **/
        public function actionGetPoll()
        {
             $id = $_POST['id'];
            $users=Candidate::model()->findAll(array('order'=>'poll desc','limit'=>3));
            foreach ($users as $key => $value) {
                if($value['id']===$id){
                    echo json_encode(array('code'=> 1 ));
                    exit;
                }
            }
             echo json_encode(array('code'=> 0 ));
        }
 
        /**
         * 得到Ip 
         *
         * @return void
         * @author 
         **/ 
        // public function getIP() {
        //     $ip = $_SERVER['REMOTE_ADDR'];
        //     if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
        //         $ip = $_SERVER['HTTP_CLIENT_IP'];
        //     } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        //         foreach ($matches[0] AS $xip) {
        //             if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
        //                 $ip = $xip;
        //                 break;
        //             }
        //         }
        //     }
        //     return $ip;
        // }
 
/*
通过淘宝API接口查询客户端地址
调用淘宝的API接口http://ip.taobao.com/service/getIpInfo.php?ip=ip地址
*/
// $ip=get_ip_data();

// function get_ip_data(){   
//     $ip=file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".get_client_ip());
//     $ip = json_decode($ip);
//     if($ip->code){
//         return false;
//     }
//     $data = (array) $ip->data;
//     return $data;
// }

//取客户端 ip
function getIP()
{
    if (isset($_SERVER['HTTP_CLIENT_IP']) and !empty($_SERVER['HTTP_CLIENT_IP']))
    {
        return $_SERVER['HTTP_CLIENT_IP'];
    }
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
        return strtok($_SERVER['HTTP_X_FORWARDED_FOR'], ',');
    }
    if (isset($_SERVER['HTTP_PROXY_USER']) and !empty($_SERVER['HTTP_PROXY_USER']))
    {
        return $_SERVER['HTTP_PROXY_USER'];
    }
    if (isset($_SERVER['REMOTE_ADDR']) and !empty($_SERVER['REMOTE_ADDR']))
    {
        return $_SERVER['REMOTE_ADDR'];
    }
    else
    {
        return "0.0.0.0";
    }
}


        /**
         * 防止直接访问投票的添加接口
         *
         * @return void
         * @author 
         **/ 
        public function VwCheckReferer(){
             $message="";
             $sReferer = "";
             $sServerName = "";
             $sReferer = ( isset( $_SERVER["HTTP_REFERER"] ) ? $_SERVER["HTTP_REFERER"] : "" );
             $sServerName = ( isset($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : "" );
             $sReferer = strtolower( trim( $sReferer ) );
             $sServerName = strtolower( trim( $sServerName ) );
             if ( "" == $sReferer ){
                 $message="为了安全，请不要直接输入地址访问本页面。"; 
             }
             else if ( substr( $sReferer, 7, strlen($sServerName) ) != $sServerName ){
                 $message="提交路径有误，禁止从站点外部提交数据。"; 
             }
             return $message;
            }


        // Uncomment the following methods and override them if needed
        /*
        public function filters()
        {
            // return the filter configuration for this controller, e.g.:
            return array(
                'inlineFilterName',
                array(
                    'class'=>'path.to.FilterClass',
                    'propertyName'=>'propertyValue',
                ),
            );
        }

        public function actions()
        {
            // return external action classes, e.g.:
            return array(
                'action1'=>'path.to.ActionClass',
                'action2'=>array(
                    'class'=>'path.to.AnotherActionClass',
                    'propertyName'=>'propertyValue',
                ),
            );
        }
        */
    }